package com.daisuxia.web.synchronization;

import java.math.BigDecimal;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.daisuxia.back.dao.ILocalDataDao;
import com.daisuxia.back.service.TaskJobMiddleService;
import com.daisuxia.back.utils.IdGen;
import com.daisuxia.back.vo.jxl.ContactList;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.pojo.AuditCenter;
import com.daisuxia.web.pojo.CreditLoanPay;
import com.daisuxia.web.pojo.CreditLoanPayDetail;
import com.daisuxia.web.pojo.CreditLoanPaySum;
import com.daisuxia.web.pojo.MmanLoanCollectionOrder;
import com.daisuxia.web.pojo.MmanUserLoan;
import com.daisuxia.web.pojo.MmanUserRela;
import com.daisuxia.web.pojo.SysUserBankCard;
import com.daisuxia.web.synchronization.dao.IDataDao;
import com.daisuxia.web.util.DateUtil;
/**
 * 处理逾期数据
 * @author gaoyuhai
 *
 */
public class OperaOverdueDataThread implements Runnable {

	private static Logger loger = Logger.getLogger(OperaOverdueDataThread.class);
	private String repaymentId;
	private IDataDao dataDao;
	private ILocalDataDao localDataDao;
	private TaskJobMiddleService taskJobMiddleService;

	private RedisUtil redisUtil;
	public OperaOverdueDataThread(String repaymentId, IDataDao dataDao,ILocalDataDao localDataDao,TaskJobMiddleService taskJobMiddleService,RedisUtil redisUtil) {
		this.repaymentId = repaymentId;
		this.dataDao = dataDao;
		this.localDataDao = localDataDao;
		this.taskJobMiddleService = taskJobMiddleService;
		this.redisUtil = redisUtil;
	}

	public OperaOverdueDataThread() {
	}

	@Override
	public void run() {
		if (StringUtils.isNotBlank(repaymentId)) {
			loger.error("sync-OperaOverdueDataThread:"+repaymentId);
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("ID", repaymentId);
			loger.info("getAssetRepayment-执行时间start"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
			HashMap<String, Object> repayment = this.dataDao.getAssetRepayment(map);
			loger.info("getAssetRepayment-执行时间end"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
			// loger.info("repayment="+repayment);
			if (null != repayment) {
				try {
					String reId = String.valueOf(repayment.get("asset_order_id"));
					HashMap<String, Object> borrowOrder = null;
					List<HashMap<String, Object>> repaymentDetalList = null;
					if (checkLoan(reId)) {
						map = new HashMap<String, String>();
						map.put("ID", repaymentId);
						loger.info("getAssetRepaymentDetail-执行时间start"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						repaymentDetalList = this.dataDao.getAssetRepaymentDetail(map);
						loger.info("getAssetRepaymentDetail-执行时间end"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						// loger.info("repaymentDetalList="+repaymentDetalList);
						map = new HashMap<String, String>();
						map.put("ORDER_ID", String.valueOf(repayment.get("asset_order_id")));
						loger.info("getAssetBorrowOrder-执行时间start"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						borrowOrder = this.dataDao.getAssetBorrowOrder(map);
						loger.info("getAssetBorrowOrder-执行时间end"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						// loger.info("borrowOrder="+borrowOrder);
						map = new HashMap<String, String>();
						map.put("USER_ID", String.valueOf(repayment.get("user_id")));
						loger.info("getUserInfo-执行时间start"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						HashMap<String, Object> userInfo = this.dataDao.getUserInfo(map);
						loger.info("getUserInfo-执行时间end"	+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						// loger.info("userInfo="+userInfo);
						loger.info("getUserCardInfo-执行时间start"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						HashMap<String, Object> cardInfo = this.dataDao.getUserCardInfo(map);
						loger.info("getUserCardInfo-执行时间end"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						// loger.info("cardInfo="+cardInfo);
						loger.info("getUserContacts-执行时间start"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						List<HashMap<String, Object>> userContactsList = this.dataDao.getUserContacts(map);
						loger.info("getUserContacts-执行时间end"+ DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						// loger.info("userContactsList="+userContactsList);
						if (null != userInfo && null != borrowOrder&& null != cardInfo&& null != repaymentDetalList) {
							saveDateToLocal(repayment, userInfo, borrowOrder,cardInfo,userContactsList);
						}
						redisUtil.delRedisKey(Constant.TYPE_OVERDUE_ + repaymentId);
						loger.info("taskJobMiddleService=派单执行时间"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
						this.taskJobMiddleService.dispatchforLoanId(String.valueOf(repayment.get("asset_order_id")));
						//派单完后再去保存用户还款详情表
						if(null != repaymentDetalList){
							String id = String.valueOf(repayment.get("id"));//还款id
							/**保存用户还款详情表*/
							saveCreditLoanPayDetail(repayment,id, repaymentDetalList);
						}
						//验证是否减免
						syncUtils.checkReduction(repayment,localDataDao);

					} else {
						map = new HashMap<String, String>();
						map.put("ORDER_ID", String.valueOf(repayment.get("asset_order_id")));
						borrowOrder = this.dataDao.getAssetBorrowOrder(map);
						map = new HashMap<String, String>();
						map.put("ID", repaymentId);
						repaymentDetalList = this.dataDao.getAssetRepaymentDetail(map);
						if (null != borrowOrder && null != repaymentDetalList) {
							updateDateToLocalForRenewal(repayment, repaymentDetalList, borrowOrder);
						}
						//验证是否减免
						syncUtils.checkReduction(repayment,localDataDao);
						redisUtil.delRedisKey(Constant.TYPE_OVERDUE_ + repaymentId);
					}
				} catch (Exception e0) {
					loger.error("run-借款loanId"+repayment.get("asset_order_id"));
					e0.printStackTrace();
				}
			}else{
				redisUtil.delRedisKey(Constant.TYPE_OVERDUE_ + repaymentId);
			}
		}
	}
	
	/**
	 * 保存数据到本地
	 * @param repaymentMap
	 * @param userInfo
	 * @param borrowOrder
	 * @param cardInfo
	 * @param userContactsList
	 */
	public void saveDateToLocal(HashMap<String,Object> repaymentMap,HashMap<String,Object> userInfo,
			HashMap<String,Object> borrowOrder,HashMap<String,Object> cardInfo,
			List<HashMap<String,Object>> userContactsList){
		if(null!=repaymentMap){
			String id = String.valueOf(repaymentMap.get("id"));//还款id
			String userId = String.valueOf(repaymentMap.get("user_id"));//userid
			String assetOrderId = String.valueOf(repaymentMap.get("asset_order_id"));//orderid借款id
			if(StringUtils.isNotBlank(id) && StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(assetOrderId)){
				/**保存用户借款表*/
				loger.info("saveMmanUserLoan-执行时间start"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
				saveMmanUserLoan(borrowOrder, repaymentMap);
				loger.info("saveMmanUserLoan-执行时间end"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
				
				/**保存用户还款表*/
				loger.info("saveCreditLoanPay-执行时间start"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
				saveCreditLoanPay(repaymentMap);
				loger.info("saveCreditLoanPay-执行时间end"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
				
//				/**保存用户还款详情表*/
//				loger.info("saveCreditLoanPayDetail-执行时间start"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
//				saveCreditLoanPayDetail(repaymentMap,id, repaymentDetalList);
//				loger.info("saveCreditLoanPayDetail-执行时间end"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
//				
				/**保存用户表*/
				if(checkUserInfo(userId)){//用户信息不存在
					loger.info("saveMmanUserInfo-start借款loanId-"+assetOrderId+"执行时间start"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
					String userFrom = String.valueOf(userInfo.get("user_from"));
					if(StringUtils.isNotBlank(userFrom)){
						userFrom = "0";
					}
					userInfo.put("user_from", userFrom);
					this.localDataDao.saveMmanUserInfo(userInfo);//保存用户信息
					loger.info("saveMmanUserInfo-借款loanId-"+assetOrderId+"执行时间end"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
					/**保存用户关系表*/
					loger.info("saveMmanUserRela-start借款loanId-"+assetOrderId+"执行时间start"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
					saveMmanUserRela(userInfo, userContactsList);
					loger.info("saveMmanUserRela-执行时间end"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
					/**保存用户银行卡*/
					loger.info("saveSysUserBankCard-start借款loanId-"+assetOrderId+"执行时间start"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
					saveSysUserBankCard(cardInfo);
					loger.info("saveSysUserBankCard-执行时间end"+DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss"));
				}else{//用户信息存在
					if(checkUserRela(userId)){//通讯录不存在
						saveMmanUserRela(userInfo, userContactsList);
					}
					/**更新银行卡*/
					updateSysUserBankCard(cardInfo);
				}
			}
		}
	}
	
	/**
	 * 更新本地数据-逾期
	 * @param repayment
	 * @param repaymentDetalList
	 * @param borrowOrder
	 */
	private void updateDateToLocalForRenewal(HashMap<String,Object> repaymentMap,List<HashMap<String,Object>> repaymentDetalList,HashMap<String,Object> borrowOrder){
		if(null!=repaymentMap){
			String id = String.valueOf(repaymentMap.get("id"));//还款id
			String assetOrderId = String.valueOf(repaymentMap.get("asset_order_id"));//orderid借款id
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("ORDER_ID", assetOrderId);
			map.put("USER_ID", repaymentMap.get("user_id"));
			MmanLoanCollectionOrder order = this.localDataDao.selectLoanOrder(map);
			if(null != order){			
				/**更新用户还款表*/
				updateCreditLoanPay(repaymentMap);
				/**保存用户还款详情表*/
				saveCreditLoanPayDetail(repaymentMap,id, repaymentDetalList);
				String status = order.getStatus();
				BigDecimal realMoney =  new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("repaymented_amount")))/100.00);
				//0:待催收 1：催收中 2：承诺还款  5：续期
				if(status.equals(Constant.STATUS_OVERDUE_FIVE)){
					map.put("STATUS", Constant.STATUS_OVERDUE_ZERO);
					/**更新用户借款表*/
					updateMmanUserLoan(borrowOrder, repaymentMap,Constant.STATUS_OVERDUE_THREE);//续期
				}
				else{
					/**更新用户借款表*/
					updateMmanUserLoan(borrowOrder, repaymentMap,null);//逾期
				}
				map.put("REAL_MONEY", realMoney);
				this.localDataDao.updateOrderStatus(map);
			}
		}
	}
	/**保存用户借款表*/
	private void saveMmanUserLoan(HashMap<String,Object> borrowOrder,HashMap<String,Object> repaymentMap){
		MmanUserLoan mmanUserLoan = new MmanUserLoan();
		mmanUserLoan.setId(String.valueOf(borrowOrder.get("id")));
		mmanUserLoan.setUserId(String.valueOf(borrowOrder.get("user_id")));
		mmanUserLoan.setLoanPyId(String.valueOf(borrowOrder.get("out_trade_no")));//第三方订单号
		mmanUserLoan.setLoanMoney(new BigDecimal(Integer.parseInt(String.valueOf(borrowOrder.get("money_amount")))/100));
		mmanUserLoan.setLoanRate(String.valueOf(borrowOrder.get("apr")));
		mmanUserLoan.setLoanPenalty(new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("plan_late_fee")))/100));
		mmanUserLoan.setLoanPenaltyRate(String.valueOf(repaymentMap.get("late_fee_apr")));
		mmanUserLoan.setLoanStatus(Constant.STATUS_OVERDUE_FOUR);//4：逾期
		mmanUserLoan.setLoanEndTime(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("repayment_time")), "yyyy-MM-dd HH:mm:ss"));//getDateTimeFormat
		mmanUserLoan.setLoanStartTime(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("credit_repayment_time")), "yyyy-MM-dd HH:mm:ss"));
		mmanUserLoan.setCreateTime(new Date());
		mmanUserLoan.setUpdateTime(new Date());
		mmanUserLoan.setDelFlag("0");//0正常1：删除
		this.localDataDao.saveMmanUserLoan(mmanUserLoan);
	}
	/**更新用户借款表*/
	private void updateMmanUserLoan(HashMap<String,Object> borrowOrder,HashMap<String,Object> repaymentMap,String status){
		MmanUserLoan mmanUserLoan = new MmanUserLoan();
		mmanUserLoan.setId(String.valueOf(borrowOrder.get("id")));
		mmanUserLoan.setUserId(String.valueOf(borrowOrder.get("user_id")));
		mmanUserLoan.setLoanPyId(String.valueOf(borrowOrder.get("out_trade_no")));//第三方订单号
		mmanUserLoan.setLoanMoney(new BigDecimal(Integer.parseInt(String.valueOf(borrowOrder.get("money_amount")))/100));
		mmanUserLoan.setLoanRate(String.valueOf(borrowOrder.get("apr")));
		mmanUserLoan.setLoanPenalty(new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("plan_late_fee")))/100));
		mmanUserLoan.setLoanPenaltyRate(String.valueOf(repaymentMap.get("late_fee_apr")));
		mmanUserLoan.setLoanStatus(status);
		mmanUserLoan.setLoanEndTime(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("repayment_time")), "yyyy-MM-dd HH:mm:ss"));//getDateTimeFormat
		mmanUserLoan.setLoanStartTime(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("credit_repayment_time")), "yyyy-MM-dd HH:mm:ss"));
		mmanUserLoan.setUpdateTime(new Date());
		this.localDataDao.updateMmanUserLoan(mmanUserLoan);
	}
	/**保存用户还款表*/
	private void saveCreditLoanPay(HashMap<String,Object> repaymentMap){
		CreditLoanPay creditLoanPay = new CreditLoanPay();
		creditLoanPay.setId(String.valueOf(repaymentMap.get("id")));
		creditLoanPay.setLoanId(String.valueOf(repaymentMap.get("asset_order_id")));
		creditLoanPay.setReceivableStartdate(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("credit_repayment_time")), "yyyy-MM-dd HH:mm:ss"));
		creditLoanPay.setReceivableDate(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("repayment_time")), "yyyy-MM-dd HH:mm:ss"));//应还时间
		creditLoanPay.setReceivableMoney(new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("repayment_amount")))/100));
		creditLoanPay.setRealMoney(new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("repaymented_amount")))/100));
		creditLoanPay.setStatus(getPayStatus(String.valueOf(repaymentMap.get("status")))); //还款状态
		creditLoanPay.setCreateDate(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("created_at")), "yyyy-MM-dd HH:mm:ss"));
		creditLoanPay.setUpdateDate(new Date());
		creditLoanPay = operaRealPenlty(repaymentMap,creditLoanPay);
		this.localDataDao.saveCreditLoanPay(creditLoanPay);
	} 
	/**更新用户还款表*/ 
	private void updateCreditLoanPay(HashMap<String,Object> repaymentMap){
		CreditLoanPay creditLoanPay = new CreditLoanPay();
		creditLoanPay.setId(String.valueOf(repaymentMap.get("id")));
		creditLoanPay.setLoanId(String.valueOf(repaymentMap.get("asset_order_id")));
		creditLoanPay.setReceivableStartdate(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("credit_repayment_time")), "yyyy-MM-dd HH:mm:ss"));
		creditLoanPay.setReceivableDate(DateUtil.getDateTimeFormat(String.valueOf(repaymentMap.get("repayment_time")), "yyyy-MM-dd HH:mm:ss"));//应还时间
		creditLoanPay.setReceivableMoney(new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("repayment_amount")))/100.00));
		creditLoanPay.setRealMoney(new BigDecimal(Integer.parseInt(String.valueOf(repaymentMap.get("repaymented_amount")))/100.00));
		creditLoanPay.setStatus(getPayStatus(String.valueOf(repaymentMap.get("status")))); //还款状态
		creditLoanPay.setUpdateDate(new Date());
		creditLoanPay = operaRealPenlty(repaymentMap,creditLoanPay);
		this.localDataDao.updateCreditLoanPay(creditLoanPay);
	}
	/**保存用户还款详情表*/
	private void saveCreditLoanPayDetail(HashMap<String, Object> repayment,String id,List<HashMap<String,Object>> repaymentDetalList){
		List<String> idList = null;
		if(null!=repaymentDetalList && 0<repaymentDetalList.size()){//首先删除已有的记录，重新添加
			HashMap<String,String> map = new HashMap<String,String>(); 
			map.put("PAY_ID", id);
//			this.localDataDao.delCreditLoanPayDetail(map);
			idList = this.localDataDao.selectCreditLoanPayDetail(map);//查询目前插入的还款记录
		}
		CreditLoanPayDetail creditLoanPayDetail =null;
		HashMap<String,Integer> amountMap = getAmountToMap(repayment);
		for(int i=0;i<repaymentDetalList.size();i++){
			HashMap<String,Object> repayDetail = repaymentDetalList.get(i);
			String detailId = String.valueOf(repayDetail.get("id"));
			if(checkDetailId(idList, detailId)){
				//减免罚息    如果还款类型为6，还款状态2.则更新还款表的 减免金额
				syncUtils.ReductionMoney(repayDetail,id,localDataDao);
				
				creditLoanPayDetail = new CreditLoanPayDetail();
				creditLoanPayDetail.setId(detailId);
				creditLoanPayDetail.setPayId(id);
				creditLoanPayDetail.setCreateDate(DateUtil.getDateTimeFormat(String.valueOf(repayDetail.get("created_at")), "yyyy-MM-dd HH:mm:ss"));
				creditLoanPayDetail.setUpdateDate(new Date());
				creditLoanPayDetail.setReturnType(String.valueOf(repayDetail.get("repayment_type")));
				creditLoanPayDetail.setRemark(String.valueOf(repayDetail.get("remark")));
				HashMap<String,String> resultMap = checkOrderByS1(repayDetail);
				if(null!=resultMap){
					String	flag = resultMap.get("sFlag");
					if(StringUtils.isNotBlank(flag)){
						creditLoanPayDetail.setS1Flag(Constant.S_FLAG);
					}
					creditLoanPayDetail.setCurrentCollectionUserId(resultMap.get("currentUserId"));
				}
				creditLoanPayDetail = operaRealPenltyDetail(amountMap, repayDetail, id,creditLoanPayDetail);
				this.localDataDao.saveCreditLoanPayDetail(creditLoanPayDetail);
			}
		}
	}
	/**
	 * 验证id是否存在list
	 * @param idList
	 * @param id
	 * @return
	 */
	private boolean checkDetailId(List<String> idList,String id){
		if(null!=idList && 0<idList.size()){
			for(int i=0;i<idList.size();i++){
				if(id.equals(idList.get(i))){
					return false;
				}
			}
			return true;
		}else{
			return true;
		}
	}
	/**
	 * 验证 纪录2-11号S1组订单到S2人手上的标志
	 * @param repayDetail
	 */
	private HashMap<String,String> checkOrderByS1(HashMap<String,Object> repayDetail){
		String payId = String.valueOf(repayDetail.get("asset_repayment_id"));//还款id
		String orderId = String.valueOf(repayDetail.get("asset_order_id"));//借款id
		String createdDate = String.valueOf(repayDetail.get("created_at"));
		HashMap<String,String> map = new HashMap<String,String>();
		map.put("PAY_ID", payId);
		map.put("ORDER_ID", orderId);
		HashMap<String,Object> orderMap = this.localDataDao.selectOrderByDetail(map);//查询ourder
		if(null!=orderMap){
			HashMap<String,String> resultMap = new HashMap<String,String>();
			try{
				String currentUserId = String.valueOf(orderMap.get("current_collection_user_id"));
				String sFlag = String.valueOf(orderMap.get("s1_flag"));
				int overdueDays = Integer.parseInt(String.valueOf(orderMap.get("overdueDays")));
				if(StringUtils.isNotBlank(sFlag)){
					if(sFlag.equals(Constant.S_FLAG)){
						boolean bool = operaSflag(createdDate,overdueDays);
						if(bool){
							resultMap.put("sFlag", Constant.S_FLAG);
							resultMap.put("currentUserId", currentUserId);
							return resultMap;
						}
					}
				}
				resultMap.put("currentUserId", currentUserId);
			}catch(Exception e){
				e.printStackTrace();
			}
			return resultMap;
		}
		return null;
	}
	
	/**
	 * 计算是否在s1里
	 * @param createdDate
	 * @param overdueDays
	 */
	private boolean operaSflag(String createdDate, int overdueDays) {
		int days = DateUtil.getDateFormats(createdDate,"yyyy-MM-dd HH:mm:ss");//还款时间减去当前时间
		int sDay = overdueDays-days;//逾期的天数-还款延迟天数
		if(sDay<=10){
			return true;
		}
		return false;
	}
	/**
	 * 保存用户通讯录
	 * @param userInfo
	 * @param userContactsList
	 */
	private void saveMmanUserRela(HashMap<String,Object> userInfo,List<HashMap<String,Object>> userContactsList){
		List<ContactList> contactList = null;
		try{
			contactList = JxlJsonUtil.operaJxlDetail(String.valueOf(userInfo.get("jxl_detail")));
		}catch(Exception e){
			loger.info("jxldetail - exception...");
		}
		String userId = String.valueOf(userInfo.get("id"));
		MmanUserRela mmanUserRela = null;
		mmanUserRela = new MmanUserRela();//保存user表中的联系人1
		String phoneNumO = String.valueOf(userInfo.get("first_contact_phone"));
		mmanUserRela.setId(IdGen.uuid());
		mmanUserRela.setUserId(userId);
		mmanUserRela.setContactsKey("1");
		mmanUserRela.setInfoName(String.valueOf(userInfo.get("first_contact_name")));
		mmanUserRela.setInfoValue(phoneNumO);
		mmanUserRela.setRelaKey(String.valueOf(userInfo.get("frist_contact_relation")));//联系人关系
		mmanUserRela.setDelFlag("0");//删除标记（''1''-已删除，''0''正常）
		if(null!=contactList && 0<contactList.size()){
			for(int i=0;i<contactList.size();i++){
				ContactList contact = contactList.get(i);
				if(phoneNumO.equals(contact.getPhone_num().trim())){
					mmanUserRela.setPhoneNumLoc(contact.getPhone_num_loc());//归属地
					int callcnt = 0;
					try{
						callcnt =Integer.parseInt(String.valueOf(contact.getCall_cnt()));
					}catch(Exception e){}
					mmanUserRela.setCallCnt(callcnt);//联系次数
					int CallOutCnt = 0;
					try{
						CallOutCnt =Integer.parseInt(String.valueOf(contact.getCall_out_cnt()));
					}catch(Exception e){}
					mmanUserRela.setCallOutCnt(CallOutCnt);//主叫次数
					
					int CallInCnt = 0;
					try{
						CallInCnt =Integer.parseInt(String.valueOf(contact.getCall_in_cnt()));
					}catch(Exception e){}
					mmanUserRela.setCallInCnt(CallInCnt);//被叫次数
					
					mmanUserRela.setCallLen(JxlJsonUtil.getCallLen(contact.getCall_len()));//联系时间-分
					mmanUserRela.setCallOutLen(JxlJsonUtil.getCallLen(contact.getCall_out_len()));//主叫时间-分
					mmanUserRela.setCallInLen(JxlJsonUtil.getCallLen(contact.getCall_in_len()));//被叫时间-分
					break;
				}
			}
		}
		this.localDataDao.saveMmanUserRela(mmanUserRela);
		
		mmanUserRela = new MmanUserRela();//保存user表中的联系人2
		String phoneNumT = String.valueOf(userInfo.get("second_contact_phone"));
		mmanUserRela.setId(IdGen.uuid());
		mmanUserRela.setUserId(userId);
		mmanUserRela.setContactsKey("2");
		mmanUserRela.setInfoName(String.valueOf(userInfo.get("second_contact_name")));
		mmanUserRela.setInfoValue(phoneNumT);
		mmanUserRela.setRelaKey(String.valueOf(userInfo.get("second_contact_relation")));//联系人关系
		mmanUserRela.setDelFlag("0");//删除标记（''1''-已删除，''0''正常）
		if(null!=contactList && 0<contactList.size()){
			for(int i=0;i<contactList.size();i++){
				ContactList contact = contactList.get(i);
				if(phoneNumT.equals(contact.getPhone_num().trim())){
					mmanUserRela.setPhoneNumLoc(contact.getPhone_num_loc());//归属地
					int callcnt = 0;
					try{
						callcnt =Integer.parseInt(String.valueOf(contact.getCall_cnt()));
					}catch(Exception e){}
					mmanUserRela.setCallCnt(callcnt);//联系次数
					int CallOutCnt = 0;
					try{
						CallOutCnt =Integer.parseInt(String.valueOf(contact.getCall_out_cnt()));
					}catch(Exception e){}
					mmanUserRela.setCallOutCnt(CallOutCnt);//主叫次数
					
					int CallInCnt = 0;
					try{
						CallInCnt =Integer.parseInt(String.valueOf(contact.getCall_in_cnt()));
					}catch(Exception e){}
					mmanUserRela.setCallInCnt(CallInCnt);//被叫次数
					
					mmanUserRela.setCallLen(JxlJsonUtil.getCallLen(contact.getCall_len()));//联系时间-分
					mmanUserRela.setCallOutLen(JxlJsonUtil.getCallLen(contact.getCall_out_len()));//主叫时间-分
					mmanUserRela.setCallInLen(JxlJsonUtil.getCallLen(contact.getCall_in_len()));//被叫时间-分
					break;
				}
			}
		}
		this.localDataDao.saveMmanUserRela(mmanUserRela);
		
		for(int i=0;i<userContactsList.size();i++){
			String phone =null;
			try{
				HashMap<String,Object> userRela = userContactsList.get(i);
				mmanUserRela = new MmanUserRela();
				phone = String.valueOf(userRela.get("contact_phone"));
				mmanUserRela.setId(IdGen.uuid());
				mmanUserRela.setUserId(userId);
				mmanUserRela.setInfoName(String.valueOf(userRela.get("contact_name")));
				mmanUserRela.setInfoValue(phone);
				mmanUserRela.setDelFlag("0");//删除标记（''1''-已删除，''0''正常）
				if(null!=contactList && 0<contactList.size()){
					for(int j=0;j<contactList.size();j++){
						ContactList contact = contactList.get(j);
						if(phone.equals(contact.getPhone_num().trim())){
							mmanUserRela.setPhoneNumLoc(contact.getPhone_num_loc());//归属地
							int callcnt = 0;
							try{
								callcnt =Integer.parseInt(String.valueOf(contact.getCall_cnt()));
							}catch(Exception e){}
							mmanUserRela.setCallCnt(callcnt);//联系次数
							int CallOutCnt = 0;
							try{
								CallOutCnt =Integer.parseInt(String.valueOf(contact.getCall_out_cnt()));
							}catch(Exception e){}
							mmanUserRela.setCallOutCnt(CallOutCnt);//主叫次数
							
							int CallInCnt = 0;
							try{
								CallInCnt =Integer.parseInt(String.valueOf(contact.getCall_in_cnt()));
							}catch(Exception e){}
							mmanUserRela.setCallInCnt(CallInCnt);//被叫次数
							
							mmanUserRela.setCallLen(JxlJsonUtil.getCallLen(contact.getCall_len()));//联系时间-分
							mmanUserRela.setCallOutLen(JxlJsonUtil.getCallLen(contact.getCall_out_len()));//主叫时间-分
							mmanUserRela.setCallInLen(JxlJsonUtil.getCallLen(contact.getCall_in_len()));//被叫时间-分
							break;
						}
					}
				}
				this.localDataDao.saveMmanUserRela(mmanUserRela);
			}catch (Exception e){
				loger.error("联系人信息错误：当前userId"+userId+"错误值："+phone,e);
			}
		}
	}
	/**保存用户银行卡*/
	private void saveSysUserBankCard(HashMap<String,Object> cardInfo){
//		DataSourceContextHolder.setDbType("dataSource");
		SysUserBankCard bankCard = new SysUserBankCard();
		bankCard.setId(IdGen.uuid());
		bankCard.setUserId(String.valueOf(cardInfo.get("user_id")));
		bankCard.setBankCard(String.valueOf(cardInfo.get("card_no")));
		bankCard.setDepositBank(String.valueOf(cardInfo.get("bank_name")));
		bankCard.setBankInstitutionNo(String.valueOf(cardInfo.get("bank_id")));
		bankCard.setName(String.valueOf(cardInfo.get("open_name")));
		bankCard.setMobile(String.valueOf(cardInfo.get("phone")));
		bankCard.setCityName(String.valueOf(cardInfo.get("bank_address")));
		this.localDataDao.saveSysUserBankCard(bankCard);
	}
	/**更新银行卡*/
	private void updateSysUserBankCard(HashMap<String,Object> cardInfo){
		SysUserBankCard bankCard = new SysUserBankCard();
		bankCard.setUserId(String.valueOf(cardInfo.get("user_id")));
		bankCard.setBankCard(String.valueOf(cardInfo.get("card_no")));
		bankCard.setDepositBank(String.valueOf(cardInfo.get("bank_name")));
		bankCard.setBankInstitutionNo(String.valueOf(cardInfo.get("bank_id")));
		bankCard.setName(String.valueOf(cardInfo.get("open_name")));
		bankCard.setMobile(String.valueOf(cardInfo.get("phone")));
		bankCard.setCityName(String.valueOf(cardInfo.get("bank_address")));
		this.localDataDao.updateSysUserBankCard(bankCard);
	}
	
	/**
	 * 获取状态
	 * @return
	 */
	public int getPayStatus(String status){
		/**
		 * 还款状态（3，4，5，6，7对应S1，S2，M1-M2，M2-M3，M3+对应1-10,11-30（1），1个月-2个月，2个月-3个月，3个月+）
		 * public static final int CREDITLOANPAY_OVERDUEA = 3;// 逾期1到10天S1
			public static final int CREDITLOANPAY_OVERDUEB = 4;// 逾期11到30天S2
			public static final int CREDITLOANPAY_OVERDUEC = 5;// 逾期31到60天M1-M2
			public static final int CREDITLOANPAY_OVERDUED = 6;// 逾期61到90天M2-M3
			public static final int CREDITLOANPAY_OVERDUEE = 7;// 逾期大于90天 M3+
			public static final int CREDITLOANPAY_OVERDUE_UNCOMPLETE = 8;// 续期（该状态催收员不能操作）
			public static final int CREDITLOANPAY_COMPLETE = 2;// 已还款
		 */
		if (Constant.STATUS_HKZ.equals(status)){
			return Constant.CREDITLOANPAY_OVERDUE_UNCOMPLETE;
		} else if (Constant.STATUS_YYQ.equals(status) || Constant.STATUS_YHZ.equals(status)) {
			return Constant.CREDITLOANPAY_OVERDUEA;
		} else {
			return Constant.CREDITLOANPAY_COMPLETE;
		}
	}
	/**
	 * 获取相应金额
	 * @param repaymentMap
	 * @return
	 */
	public HashMap<String,Integer> getAmountToMap(HashMap<String,Object> repaymentMap){
		HashMap<String,Integer> map = new HashMap<String,Integer>();
		int repaymentAmount = Integer.parseInt(String.valueOf(repaymentMap.get("repayment_amount")));//总还款金额
		map.put("repaymentAmount", repaymentAmount);
		int planLateFee = Integer.parseInt(String.valueOf(repaymentMap.get("plan_late_fee")));//滞纳金
		map.put("planLateFee", planLateFee);
		int repaymentedAmount = Integer.parseInt(String.valueOf(repaymentMap.get("repaymented_amount")));//已还款金额
		map.put("repaymentedAmount", repaymentedAmount);
		int receivablePrinciple = repaymentAmount - planLateFee;// 应还本金
		map.put("receivablePrinciple", receivablePrinciple);
		// 实收的利息 = 已还金额 - 应还本金
		int realPenlty = repaymentedAmount - receivablePrinciple;
		map.put("realPenlty", realPenlty);
		return map;
	}
	
	/**
	 * 计算还款
	 */
	public CreditLoanPay operaRealPenlty(HashMap<String,Object> repaymentMap,CreditLoanPay creditLoanPay){
		int repaymentAmount = Integer.parseInt(String.valueOf(repaymentMap.get("repayment_amount")));//总还款金额
		int planLateFee = Integer.parseInt(String.valueOf(repaymentMap.get("plan_late_fee")));//滞纳金
		int repaymentedAmount = Integer.parseInt(String.valueOf(repaymentMap.get("repaymented_amount")));//已还款金额
		
		int receivablePrinciple = repaymentAmount - planLateFee;// 应还本金
		
		// 实收的利息 = 已还金额 - 应还本金
		int realPenlty = repaymentedAmount - receivablePrinciple;
		
		if(realPenlty <= 0){
			creditLoanPay.setReceivablePrinciple(new BigDecimal((receivablePrinciple - repaymentedAmount) / 100.00));//剩余应还本金
			creditLoanPay.setReceivableInterest(new BigDecimal(planLateFee/100.00));//剩余应还罚息
			creditLoanPay.setRealgetPrinciple(new BigDecimal(repaymentedAmount/100.00));//实收本金
			creditLoanPay.setRealgetInterest(new BigDecimal(0));//实收罚息
		}else{
			creditLoanPay.setReceivablePrinciple(new BigDecimal(0));//剩余应还本金
			creditLoanPay.setReceivableInterest(new BigDecimal((repaymentAmount-repaymentedAmount)/100.00));//剩余应还罚息
			creditLoanPay.setRealgetPrinciple(new BigDecimal((repaymentedAmount-realPenlty)/100.00));//实收本金
			creditLoanPay.setRealgetInterest(new BigDecimal(realPenlty/100.00));//实收罚息
		}
		return creditLoanPay;
	}
	/**
	 * 计算还款详情
	 */
	public CreditLoanPayDetail operaRealPenltyDetail(HashMap<String,Integer> amountMap,HashMap<String,Object> repayDetail,String payId,CreditLoanPayDetail creditLoanPayDetail){
		int repaymentAmount = amountMap.get("repaymentAmount");//总还款金额
		int planLateFee = amountMap.get("planLateFee");//滞纳金
		int repaymentedAmount = amountMap.get("repaymentedAmount");//已还款金额
		
		int receivablePrinciple = repaymentAmount - planLateFee;// 应还本金
		
		int trueRepaymentMoney = Integer.parseInt(String.valueOf(repayDetail.get("true_repayment_money")));//还款金额，从库中传过来
		
		int detailCount = localDataDao.getDetailCount(payId);//还款详情表中payId还款条数
		
		if(detailCount == 0){
			if(trueRepaymentMoney >= receivablePrinciple){
				creditLoanPayDetail.setRealMoney(new BigDecimal(receivablePrinciple/100.00));//实收本金
				int realPenlty = trueRepaymentMoney-receivablePrinciple;//实收罚息
				creditLoanPayDetail.setRealPenlty(new BigDecimal(realPenlty/100.00));
				creditLoanPayDetail.setRealPrinciple(new BigDecimal(0));
				int realInterest = planLateFee-realPenlty;
				creditLoanPayDetail.setRealInterest(new BigDecimal(realInterest/100.00));
			}else{
				creditLoanPayDetail.setRealMoney(new BigDecimal(trueRepaymentMoney/100.00));
				creditLoanPayDetail.setRealPenlty(new BigDecimal(0));
				creditLoanPayDetail.setRealPrinciple(new BigDecimal((receivablePrinciple-trueRepaymentMoney)/100.00));
				creditLoanPayDetail.setRealInterest(new BigDecimal(planLateFee/100.00));
			}
			
		}else{
			CreditLoanPaySum creditLoanPaySum = localDataDao.sumRealMoneyAndPenlty(payId);
			int sumRealMoney = creditLoanPaySum.getSumRealMoney().intValue()*100;//总实收本金
			int sumRealPenlty = creditLoanPaySum.getSumRealPenlty().intValue()*100;//总实收罚息
			if(sumRealMoney >= receivablePrinciple){
				creditLoanPayDetail.setRealMoney(new BigDecimal(0));
				creditLoanPayDetail.setRealPenlty(new BigDecimal(trueRepaymentMoney/100.00));
				creditLoanPayDetail.setRealPrinciple(new BigDecimal(0));
				creditLoanPayDetail.setRealInterest(new BigDecimal((planLateFee-sumRealPenlty-trueRepaymentMoney)/100.00));
			}else{
				
				if((sumRealMoney+trueRepaymentMoney)<receivablePrinciple){
					creditLoanPayDetail.setRealMoney(new BigDecimal(trueRepaymentMoney/100));
					creditLoanPayDetail.setRealPenlty(new BigDecimal(0));
					int realPrinciple = receivablePrinciple-(sumRealMoney+trueRepaymentMoney);//剩余应还本金
					creditLoanPayDetail.setRealPrinciple(new BigDecimal(realPrinciple/100.00));
					creditLoanPayDetail.setRealInterest(new BigDecimal(planLateFee/100.00));
				}else{
					int realPenlty = sumRealMoney+trueRepaymentMoney-receivablePrinciple;//实收罚息
					creditLoanPayDetail.setRealMoney(new BigDecimal((trueRepaymentMoney-realPenlty)/100.00));
					creditLoanPayDetail.setRealPenlty(new BigDecimal(realPenlty/100.00));
					creditLoanPayDetail.setRealPrinciple(new BigDecimal(0));
					creditLoanPayDetail.setRealInterest(new BigDecimal((planLateFee-realPenlty)/100.00));
				}
			}
			
		}
		return creditLoanPayDetail;
	}
	

	/**
	 * 验证是否重复入库or是否存在
	 * 
	 * @return
	 */
	public boolean checkLoan(String id){
		if(StringUtils.isNotBlank(id)){
			HashMap<String,String> map = new HashMap<String,String>();
			map.put("ID", id);
			int count = this.localDataDao.checkLoan(map);
			if(count>0){
				return false;
			}
			return true;
		}
		return false;
	}
	/**
	 * 验证用户是否存在
	 * 
	 * @return
	 */
	public boolean checkUserInfo(String id){
		if(StringUtils.isNotBlank(id)){
			HashMap<String,String> map = new HashMap<String,String>();
			map.put("ID", id);
			int count = this.localDataDao.checkUserInfo(map);
			if(count>0){
				return false;
			}
			return true;//不存在
		}
		return false;
	}
	/**
	 * 验证用户联系人是否存在
	 * 
	 * @return
	 */
	public boolean checkUserRela(String id){
		if(StringUtils.isNotBlank(id)){
			HashMap<String,String> map = new HashMap<String,String>();
			map.put("ID", id);
			int count = this.localDataDao.checkUserRela(map);
			if(count>0){
				return false;
			}
			return true;//不存在
		}
		return false;
	}
	
	
}
